package com.fangzhi.conf;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fangzhi.mobel.vo.LoginVo;
import com.fangzhi.utils.GlobalParam;
import com.fangzhi.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author admin
 */
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {


    private StringRedisTemplate stringRedisTemplate;
    public JWTInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception{
        String token = request.getHeader(GlobalParam.COOKIE_VALUE);
        if (!StringUtils.hasText(token) || !JwtUtil.validateToken(token))
            return Error401(response);
        try {
            String loginVo = stringRedisTemplate.opsForValue().get(token);
            LoginVo logInVo = JSON.parseObject(loginVo, LoginVo.class);
            if (null == logInVo)
                return Error401(response);
            GlobalParam.LOGIN_ACCOUNT_INFO.set(logInVo);
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return Error401(response);
    }

    public Boolean Error401(HttpServletResponse response) throws IOException {
        JSONObject json = new JSONObject();
        json.put("message","登录过期,请重新登录");
        json.put("request_code",3000);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().append(json.toJSONString());
        return false;
    }
}
